﻿using AutoMapper;
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zhaoxi.MSACommerce.UserService.Core;
using Zhaoxi.MSACommerce.UserService.Core.Entites;
using ZhaoXi.MSACommerce.SharedKenel.Messaging;
using ZhaoXi.MSACommerce.UserService.Infrastructure;
using ZhaoXi.MSACommerce.UserService.Infrastructure.Tools;

namespace ZhaoXi.MSACommerce.UserService.UserCases.Commands;

public record CreateUserCommand(string Username,string Password,string? phone):ICommand<Result>;

public class CreateUserCommandValidator:AbstractValidator<CreateUserCommand>
{
    public CreateUserCommandValidator()
    {
        RuleFor(command => command.Username)
            .NotEmpty()
            .MaximumLength(DataSchemaConstants.DefaultUsernameMaxLength);
        RuleFor(command => command.Password)
            .NotEmpty()
            .MinimumLength(6)
            .MaximumLength(DataSchemaConstants.DefaultPasswordMaxLength);

        RuleFor(command => command.phone)
            .Length(DataSchemaConstants.DefaultPhoneLength);
    }
}
public class CreateUserCommandHanlder(UserDbContext dbContext, IMapper maper) : ICommandHandler<CreateUserCommand, Result>
{
    public async Task<Result> Handle(CreateUserCommand request, CancellationToken cancellationToken)
    {
        var userExists=await dbContext.TbUsers
            .AnyAsync(user=>user.Username == request.Username,cancellationToken);

        if (userExists)
        {
            return Result.Failure("用户名已存在");
        }

        var user = maper.Map<TbUser>(request);

        user.Salt=Md5Helper.MD5EncodingOnly(request.Username);
        user.Password = Md5Helper.MD5EncodingWithSalt(user.Password, user.Salt);
        dbContext.TbUsers.Add(user);
        var count = await dbContext.SaveChangesAsync(cancellationToken);

        return count != 1 ? Result.Failure("用户注册失败") : Result.Success();
    }
}

